package univ.paris.ouest.controle;

import javax.servlet.http.HttpSession;

import univ.paris.ouest.command.AthentificationCommand;

import univ.paris.ouest.validator.AthentificationValidator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;

import univ.paris.ouest.domaine.UserLogin;
import univ.paris.ouest.domaine.user.User;
import univ.paris.ouest.service.IUserLogin;
import univ.paris.ouest.service.user.IUser;

@Controller
public class AuthentificationController {
	@Autowired
	private IUser userManager;
	@Autowired
	private IUserLogin userLoginManager;
	@Autowired
	private AthentificationValidator validator;
	private User userSession = new User();//il faut le changer

	@RequestMapping(value="/connection", method=RequestMethod.POST)
	public String authentifier(@ModelAttribute("authentificationCommand") AthentificationCommand authCommand,BindingResult result,SessionStatus status,HttpSession session){
		this.validator.validate(authCommand, result);
		if(result.hasErrors()){
			return "authentification";//retour vers la page d'authentification
		}
		else{
		    UserLogin userLogin = new UserLogin();
		    userLogin.setEmail(authCommand.getEmail());userLogin.setPwd(authCommand.getPwd());
		    userLogin= this.userLoginManager.getUserLogin(userLogin);
		    if(userLogin!=null){
			   userSession.setUserLogin(userLogin);
			   userSession= this.userManager.getUser(userSession);
			   session.setAttribute("userSession",userSession);
			   return "espaceCovoiturage";
			     }
		   else{// userLogin=null
		     return "authentification";//retour vers la page authentification
		    }
		}
	}

}